<?php
/**
 * 后台模型管理控制器   
 * ModelController.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * -------------------------------
 * 
 * @package xcs
 * @author huangdaohai <huangdaohai.2007@163.com>
 * @version V1.0
 * @access public
 */
class ModelController extends AdminController 
{
	protected $oModel;
    protected $oModelField;
    protected $_attributeLabels;
    protected $_attributeFieldLabels;
	public function __construct($id, $module) {
	    //模型
		$this->oModel = new CmsModel();
        $this->_attributeLabels = $this->oModel->attributeLabels();
        //字段模型
        $this->oModelField = new CmsModelField();
        $this->_attributeFieldLabels = $this->oModelField->attributeLabels();
		return parent::__construct($id, $module);
	}	
	/**
	 * ModelController::actionIndex()
	 * 
	 * @return void
	 */
	public function actionIndex() {
	    $aParams['pagesize'] = $this->pagesize;
		$aParams['page'] = $this->_request->getQuery('page' ,0);
		$aResult = $this->oModel->getList($aParams);
        $aResult['params'] = $aParams;	
		$this->render('index', $aResult);
	}
    /**
     * ModelController::actionAdd() 添加模型
     * 
     * @return void
     */
    public function actionAdd(){
        //表单提交
        $aPostData = $this->_request->getPost('CmsModel');
        if( !empty($aPostData) ){
            //开始提交表单
            $aPostData['site_id'] = 1;
            $aPostData['disable'] = 1;
            $aPostData['createtime'] = time();
            $aPostData['updatetime'] = time();
            //$this->oModel->attributes =  $aPostData;
            //$this->oModel->save();
            $modelid = $this->oModel->saveData($aPostData);
            //echo $modelid;exit;
            //获取自动创建表的SQL文件 \\\
            $sSqlPath = ROOT_DIR.DIRECTORY_SEPARATOR.'protected'.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR.'model.sql';
			$model_sql = file_get_contents($sSqlPath);
            //表前缀
			$tablepre = Yii::app()->db->tablePrefix . 'cms_';
			$tablename = $aPostData['table_name'];
            //替换SQL文件对应变量
			$model_sql = str_replace('$basic_table', $tablepre.$tablename, $model_sql);
			$model_sql = str_replace('$table_model_field',$tablepre.'model_field', $model_sql);
			$model_sql = str_replace('$model_id',$modelid,$model_sql);
			//执行SQL语句
			$this->oModel->executeSQL($model_sql);
			if( $modelid ){
			    //$alert="SendWebMsg('success','数据模型编辑成功','".$this->createUrl('model/index')."')";
                $this->showMessage(0 ,'数据模型添加成功' ,$this->createUrl('model/index'));
			}else{
				//$alert="SendWebMsg('error','创建模型失败，你检查输出信息是否有错误')";
                $this->showMessage(0 ,'创建模型失败，你检查输出信息是否有错误' ,$this->createUrl('model/index'));
			}
            Yii::app()->getClientScript()->registerScript('msg',$alert,CClientScript::POS_END);          
        }
        //获取站点所有可用模板
        $aTemplate = Yii::app()->admincommon->getTemplateList();
        $aTemplateList = array('0'=>'请选择');
        if( ! empty( $aTemplate ) ){
            foreach( $aTemplate as $aVal ){
                $aTemplateList[$aVal['dirname']] = $aVal['name'];
            }
        }
        $aData = array('category'=>array() ,'list'=>array() ,'show'=>array());
        $this->render('_form', array('aTemplateList'=>$aTemplateList ,'aTemplate'=>$aData));
    }
    /**
     * ModelController::actionEdit() 编辑
     * 
     * @return void
     */
    public function actionEdit(){
        $iModelId = $this->_request->getQuery('model_id' ,0);
        $this->oModel = $this->oModel->findByPk($iModelId);
        $aPostData = $this->_request->getPost('CmsModel');
        if( !empty($aPostData) ){
            //开始提交表单
            $aPostData['updatetime'] = time();
            //$this->oModel->attributes =  $aPostData;
            //$this->oModel->save();
            $modelid = $this->oModel->saveData($aPostData);
			if( $modelid ){
			    //$alert="SendWebMsg('success','数据模型编辑成功','".$this->createUrl('model/index')."')";
                $this->showMessage(0 ,'数据模型编辑成功' ,$this->createUrl('model/index'));
			}else{
				//$alert="SendWebMsg('error','创建模型失败，你检查输出信息是否有错误')";
                $this->showMessage(0 ,'编辑模型失败，你检查输出信息是否有错误' ,$this->createUrl('model/index'));
			}
            //Yii::app()->getClientScript()->registerScript('msg',$alert,CClientScript::POS_END);
        }
        //获取当前主题模板数组
        $aTemplate = Yii::app()->admincommon->getTemplateList();
        $aTemplateList = array('0'=>'请选择');
        if( ! empty( $aTemplate ) ){
            foreach( $aTemplate as $aVal ){
                $aTemplateList[$aVal['dirname']] = $aVal['name'];
            }
        }
        $sTemplate = $this->oModel->default_style; 
        $aData = Yii::app()->admincommon->getHandleTemplateList($sTemplate);
        //echo '<pre>';
        //print_r($aData);exit;
        $this->render('_form', array('aTemplateList'=>$aTemplateList ,'aTemplate'=>$aData));
    }
    /**
     * ModelController::actionAjaxTemplateList() 获取风格下模板
     * 
     * @return void
     */
    public function actionAjaxTemplateList(){
        $aResulte = $aData = $aHtml = array();
        $sTemplate = $this->_request->getQuery('sTemplate');
        $aResulte = 
        $aData = Yii::app()->admincommon->getHandleTemplateList($sTemplate);
        if( ! empty( $aData['category'] ) ){
            //根据对应栏目生成HTML
            $aHtml['category'] = Form::select($aData['category'] ,0 ,"name='CmsModel[category_template]' data-rules='{required:true}'");
            $aHtml['list'] = Form::select($aData['list'] ,0 ,"name='CmsModel[list_template]' data-rules='{required:true}'");
            $aHtml['show'] = Form::select($aData['show'] ,0 ,"name='CmsModel[show_template]' data-rules='{required:true}'");
            $aHtml['page'] = Form::select($aData['page'] ,0 ,"name='CmsModel[page_template]' data-rules='{required:true}'");
            $aResulte['err'] = 0;
            $aResulte['msg'] = 'success';
            $aResulte['data']  = $aHtml;
        } else {
            $aResulte['err'] = 1;
            $aResulte['msg'] = 'error';
        }      
        die(json_encode($aResulte));
        
    }      
    /**
     * ModuleController::actionAjaxDisable() 禁用启用模块
     * 
     * @return json 保存数据后结果
     */
    public function actionAjaxDisable(){
        $aResulte = array();
        $iModelId = $this->_request->getQuery('model_id' ,0);
        $this->oModel = $this->oModel->findByPk($iModelId);
        $aData = $this->oModel->attributes;
        if( ! empty( $aData ) ){
            $aData['disable'] = $aData['disable']==1 ? 2 : 1;
            $sDisable = $aData['disable']==1 ? '禁用' : '启用';
            $sTextRed = $aData['disable']==1 ? '' : 'red';
            $mResult = $this->oModel->saveData($aData);
            $html = "<a href='javascript:void(0)' class='ajaxOperateReplace $sTextRed' url='".$this->createUrl('module/ajaxDisable' ,array('model_id'=>$iModelId))."'>". $sDisable ."</a>";
            if( is_string($mResult) ){
                $aResulte = array(
                    'err' => 0 ,
                    'msg' => '状态更新成功',
                    'data' => array('html'=>$html)
                );
            } else {
                $aResulte = array(
                    'err' => 1 ,
                    'msg' => '更新状态失败'
                );
            }
        } else {
            $aResulte = array(
                'err' => 1 ,
                'msg' => '信息错误，可能原因是数据已经被删除了.'
            );
        }
        die(json_encode($aResulte));
    }
    /**
     * ModuleController::actionDelete() 删除模型，同时删除对应数据模型和字段
     * 
     * @return json $aReslut 执行结果JSON
     */
    public function actionDelete(){
        $aResult = array();
        $iModelId = $this->_request->getQuery('model_id');
        $this->oModel = $this->oModel->findByPk($iModelId);
        $sTableName = Yii::app()->db->tablePrefix .'cms_' . $this->oModel->table_name;
        //判断表下是否有数据
        $sSQL = "SELECT COUNT(id) as numbers FROM $sTableName";
        $aResult = Yii::app()->db->createCommand($sSQL)->queryRow();
        if( $aResult['numbers']>0 ){
            $aResulte = array(
                    'err' => 1 ,
                    'msg' => '模型下面有数据，不能直接删除'
                );
        }
        if( $this->oModel ){            
            $mResult = $this->oModel->deleteData($this->oModel);
            if( $mResult ){
                $aResulte = array(
                    'err' => 0 ,
                    'msg' => '删除成功'
                );
            } else {
                $aResulte = array(
                    'err' => 1 ,
                    'msg' => '删除失败'
                );
            }
        } else {
            $aResulte = array(
                'err' => 1 ,
                'msg' => '信息错误，可能原因是数据已经被删除了.'
            );
        }
        die(json_encode($aResulte));
    }
    public function actionPriview(){
        $this->pageTitle = '预览模型';
        $iModelId = $this->_request->getQuery('model_id' ,0);
        
        $oCategory = new CategoryModel();
        //print_r($oCategory->getAllCategory());exit;
        $oContentForm = new ContentForm($iModelId);
        
        $aFormInfo = $oContentForm->get();
        $this->render('_priview' ,array('forminfo'=>$aFormInfo));
    }
    /**
     * ModelController::actionModelField() 模型字段管理
     * 
     * @return void
     */
    public function actionModelField(){
		$aParams['model_id'] = $this->_request->getQuery('model_id' ,0);
		$aResult = $this->oModelField->getList($aParams);
        $this->render('modelfield' ,array('list'=>$aResult ,'params'=>$aParams));
    }
    /**
     * ModelController::actionAddField()
     * 
     * @return void
     */
    public function actionAddField(){
        $iModelId = $this->_request->getQuery('model_id' ,0);
        //提交字段
        $aPostData = $this->_request->getPost('CmsModelField');        
        //获取表名;
        $aModel = $this->oModel->getOne($iModelId);
        $sTableName = empty($aModel) ? '' : $aModel['table_name'];
        
        if( $aPostData && $sTableName ){
            //向表增加字段
            //print_r($aPostData);exit;
            $aPostData['setting'] = $this->_request->getPost('setting');
            $params['tablename'] = Yii::app()->db->tablePrefix .'cms_' .$sTableName;
            $params['field'] = $aPostData['field'];            
            $params['defaultvalue'] = isset($aPostData['setting']['defaultvalue']) ? $aPostData['setting']['defaultvalue'] : '';
            $params['maxlength'] = $aPostData['max_length'];
            $params['minnumber'] = isset($aPostData['setting']['minnumber']) ? $aPostData['setting']['minnumber'] : '';
            $params['decimaldigits'] = isset($aPostData['setting']['decimaldigits']) ? $aPostData['setting']['decimaldigits'] : '';
            
			require ROOT_DIR.'\\protected\\modules\\admin\\components\\fields\\'.$aPostData['form_type'].'\\'.'config.inc.php';
			$params['fieldtype'] = $field_type;
			if(isset($aPostData['setting']['fieldtype'])) {
				$params['fieldtype'] = $aPostData['setting']['fieldtype'];
			}
            //执行语句
            $this->oModelField->alterTableAddField($params);
            //保存数据
            //echo Yii::app()->common->array2string($aPostData['setting']);exit;
            $aPostData['field_type'] =  $params['fieldtype'];
            $aPostData['model_id'] = $iModelId;
            //unset($aPostData['setting']);
            $this->oModelField->attributes = $aPostData;
            $this->oModelField->setting = Yii::app()->common->array2string($aPostData['setting']);
            $this->oModelField->issystem = 2;
            $this->oModelField->isnull = ($aPostData['min_length'] > 0) ? 2 : 1;
            $this->oModelField->disable = 1;
            $this->oModelField->sort = 0;
            if(  $this->oModelField->save() ){
			    $alert="SendWebMsg('success','添加字段成功','".$this->createUrl('model/modelfield' ,array('model_id'=>$iModelId))."')";
			}else{
				$alert="SendWebMsg('error','添加字段失败'".var_dump($this->oModelField->errors).")";
			}
            Yii::app()->getClientScript()->registerScript('msg',$alert,CClientScript::POS_END);
        }
        $this->render('_addfieldform' ,array('iModelId'=>$iModelId));
    }
    /**
     * ModelController::actionEditField()
     * 
     * @return void
     */
    public function actionEditField(){        
        $iModelId = $this->_request->getQuery('model_id' ,0);        
        $iFieldId = $this->_request->getQuery('field_id');
        $this->oModelField = $this->oModelField->findByPk($iFieldId);
        $setting = Yii::app()->common->string2array($this->oModelField->setting);
        //提交字段
        $aPostData = $this->_request->getPost('CmsModelField');        
        //获取表名;
        $aModel = $this->oModel->getOne($iModelId);
        $sTableName = empty($aModel) ? '' : $aModel['table_name'];
        
        if( $aPostData && $sTableName ){ //print_r($aPostData);exit;
            $aPostData['setting'] = $this->_request->getPost('setting');
            $params['tablename'] = Yii::app()->db->tablePrefix .'cms_' .$sTableName;
            $params['field'] = $aPostData['field'];            
            $params['defaultvalue'] = isset($aPostData['setting']['defaultvalue']) ? $aPostData['setting']['defaultvalue'] : '';
            $params['maxlength'] = $aPostData['max_length'];
            $params['minnumber'] = isset($aPostData['setting']['minnumber']) ? $aPostData['setting']['minnumber'] : '';
            $params['decimaldigits'] = isset($aPostData['setting']['decimaldigits']) ? $aPostData['setting']['decimaldigits'] : '';
            $params['oldfield'] = isset($aPostData['oldfield']) ? $aPostData['oldfield'] : $aPostData['field'];
			require ROOT_DIR.'\\protected\\modules\\admin\\components\\fields\\'.$aPostData['form_type'].'\\'.'config.inc.php';
			$params['fieldtype'] = $field_type;
			if(isset($aPostData['setting']['fieldtype'])) {
				$params['fieldtype'] = $aPostData['setting']['fieldtype'];
			}
            //执行语句
            $this->oModelField->alterTableEditField($params);
            //保存数据
            //echo Yii::app()->common->array2string($aPostData['setting']);exit;
            $aPostData['field_type'] =  $params['fieldtype'];
            $aPostData['model_id'] = $iModelId;
            unset($aPostData['oldfield']);
            $this->oModelField->attributes = $aPostData;
            $this->oModelField->setting = Yii::app()->common->array2string($aPostData['setting']);
            $this->oModelField->isnull = ($aPostData['min_length'] > 0) ? 2 : 1;
            if(  $this->oModelField->save(false) ){
			    $alert="SendWebMsg('success','添加字段成功','".$this->createUrl('model/modelfield' ,array('model_id'=>$iModelId))."')";
			}else{
				$alert="SendWebMsg('error','添加字段失败'".var_dump($this->oModelField->errors).")";
			}
            Yii::app()->getClientScript()->registerScript('msg',$alert,CClientScript::POS_END);
        }
        //获取表单设置
        $sConfigPath = ROOT_DIR.'\\protected\\modules\\admin\\components\\fields\\'.$this->oModelField->form_type.'\\'.'field_form.inc.php';
        ob_start();
        include $sConfigPath;
        $data_setting = ob_get_contents();
		//$data_setting = iconv('gbk','utf-8',$data_setting);
		ob_end_clean();
        $this->render('_editfieldform' ,array('iModelId'=>$iModelId ,'setting'=>$data_setting));
    }
    /**
     * ModelController::actionDeleteField() 删除字段
     * 
     * @return void
     */
    public function actionDeleteField(){
        $iModelId = $this->_request->getQuery('model_id' ,0);        
        $iFieldId = $this->_request->getQuery('field_id');
        $this->oModelField = $this->oModelField->findByPk($iFieldId);
        $aModel = $this->oModel->getOne($iModelId);
        $sTableName = empty($aModel) ? '' : Yii::app()->db->tablePrefix . 'cms_' .$aModel['table_name'];
        //删除数据和对应表中字段
        if($this->oModelField && $this->oModelField->delete()){
            $sSQL = "ALTER TABLE $sTableName DROP COLUMN ".$this->oModelField->field;
            $sTableName && Yii::app()->db->createCommand($sSQL)->execute();
            $aResult['err'] = 0;
            $aResult['msg'] = '删除成功';
        } else {
            $aResult['err'] = 1;
            $aResult['msg'] = '删除失败';
        }
        die(json_encode($aResult));
    }
        
    /**
     * ModuleController::actionAjaxFieldDisable() 启用禁用字段
     * 
     * @return json 保存数据后结果
     */
    public function actionAjaxFieldDisable(){
        $aResulte = array();
        $iFieldId = $this->_request->getQuery('field_id' ,0);
        $this->oModelField = $this->oModelField->findByPk($iFieldId);
        $aData = $this->oModelField->attributes;
        if( ! empty( $aData ) ){
            $aData['disable'] = $aData['disable']==1 ? 2 : 1;
            $sDisable = $aData['disable']==1 ? '禁用' : '启用';
            $sTextRed = $aData['disable']==1 ? '' : 'red';
            $mResult = $this->oModelField->saveData($aData ,false);
            $html = "<a href='javascript:void(0)' class='ajaxOperateReplace $sTextRed' url='".$this->createUrl('model/ajaxFieldDisable' ,array('field_id'=>$iFieldId))."'>". $sDisable ."</a>";
            
            if( !is_array($mResult) ){
                $aResulte = array(
                    'err' => 0 ,
                    'msg' => '状态更新成功',
                    'data' => array('html'=>$html)
                );
            } else {
                $aResulte = array(
                    'err' => 1 ,
                    'msg' => '更新状态失败'
                );
            }
        } else {
            $aResulte = array(
                'err' => 1 ,
                'msg' => '信息错误，可能原因是数据已经被删除了.'
            );
        }
        die(json_encode($aResulte));
    }    
    /**
     * ModelController::actionajaxFieldSort() 字段排序
     * 
     * @return json 
     */
    public function actionajaxFieldSort(){
        $aResulte = array();
        $iFieldId = $this->_request->getQuery('field_id' ,0);
        $iSort = $this->_request->getQuery('sort' ,0);
        $this->oModelField = $this->oModelField->findByPk($iFieldId);
        $aData = $this->oModelField->attributes;
        if( ! empty( $aData ) ){
            $aData['sort'] = $iSort;
            $mResult = $this->oModelField->saveData($aData ,false);
            if( !is_array($mResult) ){
                $aResulte = array(
                    'err' => 0 ,
                    'msg' => '排序成功'
                );
            } else {
                $aResulte = array(
                    'err' => 1 ,
                    'msg' => '排序失败'
                );
            }
        } else {
            $aResulte = array(
                'err' => 1 ,
                'msg' => '排序失败，可能原因是数据已经被删除了.'
            );
        }
        die(json_encode($aResulte));
    }
    /**
     * ModelController::actionAjaxVerifyTableName()
     * 
     * @return void
     */
    public function actionAjaxVerifyTableName(){
        $aTableName = $this->_request->getQuery('CmsModel' ,array('table_name'=>''));
        if( $this->oModel->verifyFieldTableName($aTableName['table_name']) ){
            die(json_encode(array('err'=>1 ,'msg'=>$aTableName['table_name'].'表已经存在')));
        }
        die(json_encode(array('err'=>0 ,'msg'=>'success')));
    }
    /**
     * ModelController::actionAjaxVerifyField()
     * 
     * @return void
     */
    public function actionAjaxVerifyField(){
        $sss = urlencode('CmsModelField[field]');
        $ccc = $this->_request->getQueryString();
        $aField = $this->_request->getQuery('CmsModelField' ,array('field'=>''));
        if( $this->oModelField->verifyField($aField['field']) ){
            die(json_encode(array('err'=>1 ,'msg'=>$aField['field'].'字段已经存在')));
        }
        die(json_encode(array('err'=>0 ,'msg'=>'success')));
        
    }
    /**
     * ModelController::actionAjaxVerifyFieldName()
     * 
     * @return void
     */
    public function actionAjaxVerifyFieldName(){
        $aFieldName = $this->_request->getQuery('CmsModelField' ,array('field_name'=>''));
        if( $this->oModelField->verifyFieldName($aFieldName['field_name']) ){
            die(json_encode(array('err'=>1 ,'msg'=>$aFieldName['field_name'].'字段别名已经存在')));
        }
        die(json_encode(array('err'=>0 ,'msg'=>'success')));
    }
    /**
     * ModelController::actionFieldtype() 切换字段状态
     * 
     * @return json 处理结果
     */
    public function actionFieldtype(){
        //根据类型获取对应设置项
        $sFieldType = $this->_request->getQuery('fieldtype');
        $sConfigPath = ROOT_DIR.'\\protected\\modules\\admin\\components\\fields\\'.$sFieldType.'\\'.'field_form.inc.php';
        ob_start();
        include $sConfigPath;
        $data_setting = ob_get_contents();
		//$data_setting = iconv('gbk','utf-8',$data_setting);
		ob_end_clean();
        //print_r($data_setting);exit;
        $aResult['err'] = 0;
        $aResult['msg'] = 'success';
        $aResult['data'] = $data_setting;
        die(json_encode($aResult));
    }
}
?>